//
// Created by songpingwang on 25-7-8.
//
#ifndef UDATAFRAME_INL
#define UDATAFRAME_INL
#include <utility>
#include <limits>
#include "UDataBase.h"
#include "UDataFrame.h"
#include <unordered_set>
#include "UDataView.h"
#include "charset_utils.h"


namespace NDFrame {
    template<Field field, typename Comparator>
    constexpr auto UDataFrame::getCompare() {
        if constexpr (field == Field::IDX) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.idx, b.idx); };
        } else if constexpr (field == Field::X0) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.x0, b.x0); };
        } else if constexpr (field == Field::Y0) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.y0, b.y0); };
        } else if constexpr (field == Field::X1) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.x1, b.x1); };
        } else if constexpr (field == Field::Y1) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.y1, b.y1); };
        } else if constexpr (field == Field::WIDTH) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.width, b.width); };
        } else if constexpr (field == Field::HEIGHT) {
            return [](const DataItem& a, const DataItem& b) { return Comparator()(a.height, b.height); };
        } else {
            static_assert(always_false<field>::value, "Invalid field name for sorting");
            return [](const DataItem&, const DataItem&) { return false; };
        }
    }

    /**
     * @brief 对字段进行排序
     * @tparam field 字段类型
     * @param descending 是否降序
     */
    template<Field field>
    void UDataFrame::sort(const bool descending) {
        if (this->empty()) {
            throw std::runtime_error("Cannot sort an empty column.");
        }

        const auto& thisPtr = ItemPtr.get();
        std::vector<DataItem*> items(m_size);
        for (size_t i = 0; i < m_size; ++i) {
            items[i] = &thisPtr[i];
        }

        if (descending) {
            std::sort(items.begin(), items.end(),
                [](const DataItem* a, const DataItem* b) {
                    return getCompare<field, std::greater<>>()(*a, *b);
                });
        }
        else {
            std::sort(items.begin(), items.end(),
                [](const DataItem* a, const DataItem* b) {
                    return getCompare<field, std::less<>>()(*a, *b);
                });
        }

        // 原地重排列数据
        for (size_t i = 0; i < m_size; ++i) {
            const size_t j = i;
            while (items[j] != &thisPtr[j]) {
                const size_t target = items[j] - thisPtr;
                std::swap(thisPtr[j], thisPtr[target]);
                std::swap(items[j], items[target]);
                items[j] = &thisPtr[j];
            }
        }

        for (size_t i = 0; i < m_size; ++i) {
            thisPtr[i].idx = static_cast<int>(i);
        }
    }


    //////////////////////////////////////////////////////////////////////////////
    ////					对应字段值： 对数值字段进行四则运算
    //////////////////////////////////////////////////////////////////////////////


    /**
     * @brief 获取字段值减去一个数（就地修改）
     * @tparam field 字段类型
     * @return void
     */
    template<Field field>
    void UDataFrame::sub(const int num) noexcept {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_integral_v<std::remove_cv_t<FieldType>>, "sub() can only be applied to integral fields.");

        if (empty()) return;
        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < this->size(); ++i) {
            if (int& value = thisPtr[i].ValueField<field>(); value > num) {
                value -= num;
            } else {
                value = 0;
            }
        }
    }


    /**
     * @brief 获取字段值加上一个数（就地修改）
     * @tparam field 字段类型
     * @return void
     */
    template<Field field>
    void UDataFrame::add(const int num, const int max_num) noexcept {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_integral_v<std::remove_cv_t<FieldType>>, "add() can only be applied to integral fields.");

        if (empty()) return;
        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < m_size; ++i) {
            int& value = thisPtr[i].ValueField<field>();
            value += num;
            if (value > max_num) {
                value = max_num;
            }
        }
    }


    /**
     * @brief 获取字段值的平均值
     * @tparam field 字段类型
     * @return float 字段值的平均值
     */
    template<Field field>
    float UDataFrame::mean_col() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_arithmetic_v<FieldType>, "mean_col() can only be applied to numeric fields.");

        float num_mean = 0.0f;
        if (empty()) {
            return num_mean;
        }
        const auto& thisPtr = ItemPtr.get();
        for (size_t i = 0; i < m_size; ++i) {
            num_mean += static_cast<float>(thisPtr[i].ValueField<field>());
        }
        return num_mean / static_cast<float>(m_size);
    }


    /**
     * @brief 获取字段值的最大值
     * @tparam field 字段类型
     * @return size_t 字段值最大值
     */
    template<Field field>
    size_t UDataFrame::max_col() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_integral_v<std::remove_cv_t<FieldType>>, "max_col() can only be applied to integral fields.");

        if (empty()) {
            return 0;
        }
        int max_value = std::numeric_limits<int>::min();

        const auto& thisPtr = ItemPtr.get();
        for (size_t i = 0; i < m_size; ++i) {
            max_value = std::max(max_value, thisPtr[i].ValueField<field>());
        }
        return max_value;
    }


    /**
     * @brief 获取字段值的最小值
     * @tparam field 字段类型
     * @return size_t 字段值最小值
     */
    template<Field field>
    size_t UDataFrame::min_col() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_integral_v<std::remove_cv_t<FieldType>>, "min_col() can only be applied to integral fields.");

        if (empty()) { return 0;}
        int min_value = std::numeric_limits<int>::max();

        const auto& thisPtr = ItemPtr.get();
        for (size_t i = 0; i < m_size; ++i) {
            min_value = std::min(min_value, thisPtr[i].ValueField<field>());
        }

        return min_value;
    }


    /**
     * @brief 获取字段值的长度
     * @tparam field 字段类型
     * @return std::vector<size_t> 字段值的长度
     */
    template<Field field>
    std::vector<size_t> UDataFrame::len() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "len() can only be applied to string fields.");

        std::vector<size_t> lens;
        lens.reserve(m_size);
        const auto& thisPtr = ItemPtr.get();
        for (size_t i = 0; i < m_size; ++i) {
            lens.emplace_back(thisPtr[i].ValueField<field>().length());
        }
        return lens;
    }


    /**
     * @brief 获取字段值的引用
     * @tparam field 字段类型
     * @tparam T 字段值类型
     * @return std::vector<T> 字段值
     */
    template<Field field, typename T>
    std::vector<std::reference_wrapper<T>> UDataFrame::values_ref() const {
        std::vector<std::reference_wrapper<T>> result;
        if (this->empty()) {
            return result;
        }
        const auto thisPtr = ItemPtr.get();

        for (size_t i = 0; i < m_size; ++i) {
            result.push_back(std::ref(thisPtr[i].ValueField<field>()));
        }
        return result;
    }


    template<Field field, typename T>
    std::vector<T> UDataFrame::values() const {
        std::vector<T> result;
        if (this->empty()) {
            return result;
        }
        const auto& thisPtr = ItemPtr.get();

        for (size_t i = 0; i < m_size; ++i) {
            result.push_back(thisPtr[i].ValueField<field>());
        }
        return result;
    }


    //////////////////////////////////////////////////////////////////////////////
    ////                  对应字段值： 对df.txt df.txt_sep是否在容器内
    //////////////////////////////////////////////////////////////////////////////
    // API版本1：指针输出
    /**
     *
     * @tparam field 判断的字段
     * @param texts 判断字段是否在texts容器中存在
     * @param out_ptrs 字段是在texts容器的指针
     * @return 字段是在texts容器的指针容器
     */
    template<Field field>
    bool UDataFrame::is_in(const std::vector<std::string> &texts, VecItemPtr &out_ptrs) const {
        if (texts.empty()) return false;
        const std::unordered_set<std::string> text_set(texts.begin(), texts.end());
        return contains_impl<field>(text_set, &out_ptrs, nullptr);
    }


    // API版本2：数据帧输出
    template<Field field>
    bool UDataFrame::is_in(const std::vector<std::string> &texts, UDataFrame &out_df) const {
        if (texts.empty()) return false;
        const std::unordered_set<std::string> text_set(texts.begin(), texts.end());
        return contains_impl<field>(text_set, nullptr, &out_df);
    }


    // API版本3：仅检查存在性
    template<Field field>
    bool UDataFrame::contains_any(const std::vector<std::string> &texts) const {
        if (texts.empty()) return false;
        const std::unordered_set<std::string> text_set(texts.begin(), texts.end());
        return contains_impl<field>(text_set, nullptr, nullptr);
    }



    template<Field field>
    bool UDataFrame::contains_impl(
        const std::unordered_set<std::string> &text_set,
        VecItemPtr *out_ptrs,
        UDataFrame *out_df) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "contains_impl() can only be applied to string fields.");
        bool found = false;
        const auto &data = ItemPtr.get();

        if (out_df) out_df->clear();
        if (out_ptrs) out_ptrs->clear();

        for (size_t i = 0; i < m_size; ++i) {
            if (const auto &str = getTextRefConst<field>(data[i]); text_set.find(str) != text_set.end()) {
                found = true;
                if (out_ptrs) out_ptrs->push_back(&data[i]);
                if (out_df) out_df->push_back(data[i]);
            }
        }
        return found;
    }


    //////////////////////////////////////////////////////////////////////////////
    ////					对应字段值： 对df.txt df.txt_sep等文本字段进行字符拼接
    //////////////////////////////////////////////////////////////////////////////
    template<Field field>
    std::string UDataFrame::join(const std::string_view separator) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "join() can only be applied to string fields.");

        if (this->empty()) {
            return {};
        }

        const auto thisPtr = ItemPtr.get();
        if (m_size == 1) {
            return thisPtr[0].ValueField<field>();
        }

        size_t totalLength = 0;
        if (this->m_size > 1) {
            totalLength += (this->m_size - 1) * separator.size();
        }
        for (size_t i = 0; i < this->m_size; ++i) {
            totalLength += thisPtr[i].ValueField<field>().length();
        }

        std::string result;
        result.reserve(totalLength);
        result.append(thisPtr[0].ValueField<field>());

        for (size_t i = 1; i < this->m_size; ++i) {
            result.append(separator);
            result.append(thisPtr[i].ValueField<field>());
        }

        return result;
    }


    template<Field field>
    std::string UDataFrame::join_and_replace(
        const char oldChar,
        const std::string_view newChars,
        const std::string_view separator) const
    {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "join_and_replace() can only be applied to string fields.");

        if (this->empty()) {
            return {};
        }

        const auto thisPtr = ItemPtr.get();
        std::string result;
        result.reserve(this->size() * 16); // 预留一个合理的初始大小

        bool first = true;
        for (size_t i = 0; i < this->m_size; ++i) {
            if (!first && !separator.empty()) {
                result.append(separator);
            }
            const std::string& source_str = thisPtr[i].ValueField<field>();
            for (const char c : source_str) {
                if (c == oldChar) {
                    result.append(newChars);
                } else {
                    result.push_back(c);
                }
            }
            first = false;
        }

        return result;
    }


    template<Field field_src, Field field_dst>
    void UDataFrame::replace(const char oldChar, const char newChar) {
        using SrcType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_src>())>;
        using DstType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_dst>())>;
        static_assert(std::is_same_v<std::remove_cv_t<SrcType>, std::string>, "Source field for replace() must be a string.");
        static_assert(std::is_same_v<std::remove_cv_t<DstType>, std::string>, "Destination field for replace() must be a string.");

        if (this->empty()) { return;}
        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& source_text = thisPtr[i].ValueField<field_src>();
            std::string& dest_text = thisPtr[i].ValueField<field_dst>();

            if constexpr (field_src == field_dst) {
                std::replace(dest_text.begin(), dest_text.end(), oldChar, newChar);
            } else {
                dest_text = source_text;
                std::replace(dest_text.begin(), dest_text.end(), oldChar, newChar);
            }
        }
    }

    template<Field field_src, Field field_dst>
    void UDataFrame::replace(const char oldChar0, const char newChar0, const char oldChar1, const char newChar1)
    {
        using SrcType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_src>())>;
        using DstType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_dst>())>;
        static_assert(std::is_same_v<std::remove_cv_t<SrcType>, std::string>, "Source field for replace() must be a string.");
        static_assert(std::is_same_v<std::remove_cv_t<DstType>, std::string>, "Destination field for replace() must be a string.");

        if (this->empty()) { return;}

        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& source_text = thisPtr[i].ValueField<field_src>();
            std::string& dest_text = thisPtr[i].ValueField<field_dst>();

            dest_text = source_text;
            for (char& c : dest_text) {
                if (c == oldChar0) {
                    c = newChar0;
                } else if (c == oldChar1) {
                    c = newChar1;
                }
            }
        }
    }


    template<Field field_src, Field field_dst, auto pattern>
    void UDataFrame::regex_replace(const std::string_view rewrite) {
        using SrcType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_src>())>;
        using DstType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field_dst>())>;
        static_assert(std::is_same_v<std::remove_cv_t<SrcType>, std::string>, "Source field for regex_replace() must be a string.");
        static_assert(std::is_same_v<std::remove_cv_t<DstType>, std::string>, "Destination field for regex_replace() must be a string.");

        if (this->empty()) {
            return;
        }

        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& source_text = thisPtr[i].ValueField<field_src>();
            std::string& dest_text = thisPtr[i].ValueField<field_dst>();
            dest_text = global_replace<pattern>(source_text, rewrite);
        }
    }


    template<Field field, auto pattern>
    void UDataFrame::regex_extract() {
        using FieldType = std::remove_reference_t<decltype(std::declval<DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "regex_extract() can only be applied to string fields.");

        if (this->empty()) {
            return;
        }
        DataItem* thisPtr = ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            std::string& text = thisPtr[i].ValueField<field>();
            if (auto match = ctre::search<pattern>(text)) {
                if constexpr (match.count() > 1) {
                    text = std::string(match.template get<1>());
                } else {
                    text.clear();
                }
            } else {
                text.clear();
            }
        }
    }

    /**
     * @brief 从指定字段中提取匹配正则表达式第一个捕获组的内容，并创建一个新的UDataFrame。
     * @tparam field 要搜索的源字段。
     * @param pattern 包含至少一个捕获组 ( ) 的RE2正则表达式。
     * @return 一个新的UDataFrame，其中每行的'text'字段被替换为提取出的内容。
     *         如果原始行没有匹配，则不会被包含在新DataFrame中。
     */
    template<Field field, auto pattern>
    UDataFrame UDataFrame::DF_regex_extract() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "DF_regex_extract_ctre() can only be applied to string fields.");

        UDataFrame result;
        if (this->empty()) {
            return result;
        }
        result.reserve(this->size());
        const auto thisPtr = ItemPtr.get();

        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& source_text = thisPtr[i].ValueField<field>();
            if (auto match = ctre::search<pattern>(source_text)) {
                DataItem new_item = thisPtr[i];
                if constexpr (match.count() > 1) {
                    new_item.text = std::string(match.template get<1>());
                } else {
                    new_item.text = "";
                }
                result.push_back(std::move(new_item));
            }
        }
        return result;
    }


    //////////////////////////////////////////////////////////////////////////////
    ////			   专用函数 对应字段值进行过滤--返回df副本（深复制）
    //////////////////////////////////////////////////////////////////////////////
    template<Field field, auto... patterns>
    UDataFrame UDataFrame::DF_regex_match() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "DF_regex_match() can only be applied to string fields.");

        UDataFrame result;
        if (this->empty()) {
            return result;
        }
        result.reserve(this->size());

        const auto thisPtr = this->ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& field_value = thisPtr[i].ValueField<field>();
            if (matches_any<patterns...>(field_value)) {
                result.push_back(thisPtr[i]);
            }
        }
        return result;
    }


    /**
     *
     * @tparam field 处理数据结构字段
     * @tparam patterns 正则表达式
     * @tparam Comparator 大小比对函数模版
     * @param len 比对数据
     * @param compare 比对函数
     * @return 新的UDataFrame
     */
    template<Field field, auto... patterns, typename Comparator>
    UDataFrame UDataFrame::DF_reg_len_cond(size_t len, Comparator compare) const
    {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "This function can only be applied to string fields.");
        static_assert(std::is_invocable_r_v<bool, Comparator, size_t, size_t>, "Comparator must be callable with two size_t and return bool.");

        UDataFrame result;
        if (this->empty()) {
            return result;
        }
        result.reserve(this->size());

        const auto thisPtr = this->ItemPtr.get();
        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string& field_value = thisPtr[i].ValueField<field>();
            if (compare(field_value.length(), len) && matches_any<patterns...>(field_value)) {
                result.push_back(thisPtr[i]);
            }
        }
        return result;
    }


    /**
     * @brief 根据字段值进行过滤，返回df副本（深复制）
     * @tparam field 要搜索的字段。
     * @param len 字段值长度。
     * @param compare 用于比较长度的比较器。
     * @return 一个新的UDataFrame，其中每行满足给定条件的字段值。
     */
    template<Field field, typename Comparator>
    UDataFrame UDataFrame::DF_strlen_impl(size_t len, Comparator compare) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "This function can only be applied to string fields.");
        static_assert(std::is_invocable_r_v<bool, Comparator, size_t, size_t>, "Comparator must be callable with two size_t and return bool.");

        return this->DF_filter([&](const DataItem& item) {
            return compare(item.ValueField<field>().length(), len);
        });
    }


    /**
     * @brief 根据字段值进行过滤，返回df副本（深复制）
     * @tparam field 要搜索的字段。
     * @param patterns... 用于匹配的字段值的正则表达式集合。
     * @param predicate 用于判断行是否满足条件的函数。
     * @return 一个新的UDataFrame，其中每行满足给定条件的字段值。
     */
    template<Field field, auto... patterns, typename Predicate>
    UDataFrame UDataFrame::DF_regex_cond(Predicate predicate) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        static_assert(std::is_invocable_r_v<bool, Predicate, const DataItem&>, "Predicate must be a callable that takes 'const DataItem&' and returns 'bool'.");

        return this->DF_filter([&](const DataItem& item) {
            if (!predicate(item)) {
                return false;
            }
            return matches_any<patterns...>(item.ValueField<field>());
        });
    }


    //////////////////////////////////////////////////////////////////////////////
    ////			   专用函数 对应字段值进行过滤--返回符合条件的地址集合
    //////////////////////////////////////////////////////////////////////////////
    template<Field field, typename Comparator>
    bool UDataFrame::ptr_strlen_impl(VecItemPtr& out_ptr, size_t len, Comparator compare) const
    {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        return this->filter(out_ptr, [&](const DataItem& item) {
            return compare(item.ValueField<field>().length(), len);
        });
    }

    template<Field field, auto... patterns>
    bool UDataFrame::ptr_reg_impl(VecItemPtr& out_ptr) const
    {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        return this->filter(out_ptr, [&](const DataItem& item) {
            return matches_any<patterns...>(item.ValueField<field>());
        });
    }

    template<Field field, auto... patterns, typename Comparator>
    bool UDataFrame::ptr_reg_len_cond(
        VecItemPtr &out_ptr,
        size_t len, Comparator compare) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>,
                      "Regex matching can only be applied to string fields.");
        return this->filter(out_ptr, [&](const DataItem &item) {
            const auto &field_value = item.ValueField<field>();
            return compare(field_value.length(), len) && matches_any<patterns...>(field_value);
        });
    }


    template<Field field, auto... patterns, typename Predicate>
    bool UDataFrame::ptr_reg_cond(VecItemPtr& out_ptr,  Predicate predicate) const
    {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        return this->filter(out_ptr, [&](const DataItem& item) {
            return predicate(item) && matches_any<patterns...>(item.ValueField<field>());
        });
    }


    //////////////////////////////////////////////////////////////////////////////
    ////		   对UDataFrame进行首次过滤返回视图
    //////////////////////////////////////////////////////////////////////////////
    template<Field field, auto... patterns>
    UDataView UDataFrame::dv_reg_impl() const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        if (this->m_size == 0) {
            return UDataView{*this, 0, 0};
        }

        const auto& thisPtr = ItemPtr.get();
        size_t startIndex = this->m_size;

        for (size_t i = 0; i < this->m_size; ++i) {
            if (matches_any<patterns...>(thisPtr[i].ValueField<field>())) {
                if (startIndex == this->m_size) {
                    startIndex = i;
                }
            } else {
                if (startIndex != this->m_size) {
                    return UDataView{*this, startIndex, i};
                }
            }
        }

        if (startIndex != this->m_size) {
            return UDataView{*this, startIndex, this->m_size};
        }
        return UDataView{*this, 0, 0};
    }


    template<Field field, auto... patterns, typename Predicate>
    UDataView UDataFrame::dv_reg_len_cond(
             const int len, Predicate predicate) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");

        if (this->m_size == 0) return UDataView{*this, 0, 0};
        const auto& thisPtr = ItemPtr.get();
        size_t startIndex = this->m_size;

        for (size_t i = 0; i < this->m_size; ++i) {
            const std::string &field_value = thisPtr[i].ValueField<field>();
            if (predicate(field_value.size(), len) && matches_any<patterns...>(field_value)) {
                if (startIndex == this->m_size) {
                    startIndex = i;
                }
            } else {
                if (startIndex != this->m_size) {
                    return UDataView{*this, startIndex, i};
                }
            }
        }

        if (startIndex != this->m_size) {
            return UDataView{*this, startIndex, this->m_size};
        }

        return UDataView{*this, 0, 0};
    }


    template<Field field, auto... patterns, typename Predicate>
    UDataView UDataFrame::dv_reg_cond(Predicate predicate) const {
        using FieldType = std::remove_reference_t<decltype(std::declval<const DataItem>().ValueField<field>())>;
        static_assert(std::is_same_v<std::remove_cv_t<FieldType>, std::string>, "Regex matching can only be applied to string fields.");
        if (this->m_size == 0) return UDataView{*this, 0, 0};
        const auto& thisPtr = ItemPtr.get();
        size_t startIndex = this->m_size;

        for (size_t i = 0; i < this->m_size; ++i) {
            if (predicate(thisPtr[i]) && matches_any<patterns...>(thisPtr[i].ValueField<field>())) {
                if (startIndex == this->m_size) {
                    startIndex = i;
                }
            } else {
                if (startIndex != this->m_size) {
                    return UDataView{*this, startIndex, i};
                }
            }
        }

        if (startIndex != this->m_size) {
            return UDataView{*this, startIndex, this->m_size};
        }

        return UDataView{*this, 0, 0};
    }


    /*
    * 对UDataFrame进行过滤（具体过滤函数：传入具体数值）
    * - 输入 Field field_
    * - 输入 const VecRegex& regex_, int x0, int y0, int x1, int y1
    * - 返回值(符合条件的视图)：UDataView
    */
    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex() const {
        return dv_reg_impl<field, patterns...>();
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_strlen_grate( const int len) const {
        return dv_reg_len_cond<field, patterns...>(len, std::greater<>());
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_strlen_equal( const int len) const {
        return dv_reg_len_cond<field, patterns...>(len, std::equal_to<>());
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_strlen_less( const int len) const {
        return dv_reg_len_cond<field, patterns...>(len, std::less<>());
    }


    template<Field field, auto... patterns>
    MAYBE_USE UDataView
    UDataFrame::DV_loc_regex_xyxy(int x0, int y0, int x1, int y1) const {
        return dv_reg_cond<field, patterns...>([x0, y0, x1, y1](const DataItem &item) noexcept {
            return item.x0 > x0 && item.x1 < x1 && item.y0 > y0 && item.y1 < y1;
        });
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_x0x1(int x0, int x1) const {
        return dv_reg_cond<field, patterns...>(
            [x0, x1](const DataItem &item) noexcept {
                return item.x0 > x0 && item.x1 < x1;
            });
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_y0y1(int y0, int y1) const {
        return dv_reg_cond<field, patterns...>(
            [y0, y1](const DataItem &item) noexcept {
                return item.y0 > y0 && item.y1 < y1;
            });
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_x0y0_grate(int x0, int y0) const {
        return dv_reg_cond<field, patterns...>(
            [x0, y0](const DataItem &item) noexcept {
                return item.x0 > x0 && item.y0 > y0;
            });
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_x0y0_less(int x0, int y0) const {
        return dv_reg_cond<field, patterns...>(
            [x0, y0](const DataItem &item) noexcept {
                return item.x0 < x0 && item.y0 < y0;
            });
    }

    template<Field field, auto... patterns>
    MAYBE_USE UDataView UDataFrame::DV_loc_regex_x1y1(int x1, int y1) const {
        return dv_reg_cond<field, patterns...>(
            [x1, y1](const DataItem &item) noexcept {
                return item.x1 < x1 && item.y1 < y1;
            });
    }


}

#endif
